package com.mall.service.impl;



import cn.hutool.core.lang.UUID;
import com.aliyuncs.exceptions.ClientException;
import com.mall.exception.UploadFailedException;
import com.mall.properties.OssProperties;
import com.mall.service.CommonService;
import com.mall.util.OssUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;


/**
 * CommonServiceImpl
 * @author 勾新杰
 * @version 1.0
 * @date 2024/11/23 13:15
 */
@Service
@RequiredArgsConstructor
public class CommonServiceImpl implements CommonService {

    private final OssProperties ossProperties;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 文件访问路径
     */
    @Override
    public String upload(MultipartFile file) {
        // 1. 获取文件后缀
        String filename = file.getOriginalFilename();
        String suffix = Objects.requireNonNull(filename).substring(filename.lastIndexOf('.'));
        // 2. 构建新文件名
        String objectName = UUID.randomUUID() + suffix;
        // 3. 上传文件并获取 url
        try {
            return OssUtil.getUrl(
                    ossProperties.getEndpoint(),
                    ossProperties.getBucketName(),
                    ossProperties.getRegion(),
                    objectName,
                    file.getBytes());
        } catch (IOException e) {
            throw new UploadFailedException("文件上传失败");
        }
    }
}
